<template>
  <div class="pagination">
    <button
      :disabled="currentPage === 1"
      @click="$emit('changePageNo', currentPage - 1)"
    >
      上一页
    </button>
    <button
      v-if="pageComputed.start > 1"
      :class="{ active: currentPage === 1 }"
      @click="$emit('changePageNo', 1)"
    >
      1
    </button>

    <button v-if="pageComputed.start > 2">···</button>

    <button
      v-for="item in filterPage"
      :key="item"
      :class="{ active: currentPage === item }"
      @click="$emit('changePageNo', item)"
    >
      {{ item }}
    </button>

    <button v-if="totalPage > pageComputed.end + 1">···</button>
    <button
      v-if="totalPage > pageComputed.end"
      :class="{ active: currentPage === pageComputed.end }"
      @click="$emit('changePageNo', totalPage)"
    >
      {{ totalPage }}
    </button>
    <button
      :disabled="currentPage === totalPage"
      @click="$emit('changePageNo', currentPage + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["currentPage", "totalPage", "total", "continuePage"],
  computed: {
    pageComputed() {
      let start, end;
      //先判断临界值如果连续页长度大于页码总长度:起始是1 结束是总长度
      if (this.continuePage >= this.totalPage) {
        start = 1;
        end = this.totalPage;
      } else {
        //如果连续页小于总也数,先计算出来连续页的开头和结尾
        start = this.currentPage - Math.floor(this.continuePage / 2);
        end = this.currentPage + Math.floor(this.continuePage / 2);
        //判断临界值,如果start<1 则start只能最小是1
        if (start < 1) {
          start = 1;
          end = this.continuePage;
        }
        //判断临界值,如果end>total,则end最大只能是total
        if (end > this.totalPage) {
          start = this.totalPage - this.continuePage + 1;
          end = this.totalPage;
        }
      }
      return { start, end };
    },
    filterPage() {
      const arr = [];
      for (let i = 1; i <= this.pageComputed.end; i++) {
        if (i >= this.pageComputed.start) arr.push(i);
      }
      return arr;
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
